package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.common.Consts;
import com.github.aloxc.plugin.restplus.component.Variate;
import com.github.aloxc.plugin.restplus.entity.EnvironmentConfig;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.github.aloxc.plugin.restplus.navigator.RestServicesNavigator;
import com.intellij.openapi.ui.Messages;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;

public class DeleteEnvironmentListener implements ActionListener {
    private Variate variate;

    public DeleteEnvironmentListener(Variate variate){

        this.variate = variate;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        Map<String, EnvironmentConfig> env = variate.getProject().getComponent(RestServicesNavigator.class).getConfig().getEnv();
        if(env.containsKey(variate.getNameTextField().getText())){
            if(env.size() == 1){
                Messages.showMessageDialog(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.setting.exception.tips") + ":" +  variate.getNameTextField().getText(),
                        I18Bundle.getMessage("com.github.aloxc.plugin.restplus.setting.exception"), Consts.Icons.EXCEPTION);
                return;
            }
            env.remove(variate.getNameTextField().getText());
            variate.getProject().getComponent(RestServicesNavigator.class).getConfig().save(variate.getProject());
            variate.addOldEnvironmentListener((String) env.keySet().toArray()[0]);
        }else{
            Messages.showMessageDialog(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.setting.environment.delete.exception") + ":" + variate.getNameTextField().getText(),
                    I18Bundle.getMessage("com.github.aloxc.plugin.restplus.setting.exception"), Consts.Icons.EXCEPTION);
        }
    }
}
